package com.xiaoyu.lanling.feature.conversation.model

import android.text.TextUtils
import com.xiaoyu.base.data.UserInfoDataProvider
import com.xiaoyu.base.entity.ConversationEntity
import com.xiaoyu.base.model.User
import com.xiaoyu.im.datamodel.ConversationType
import com.xiaoyu.im.datamodel.LastContentWrapper
import com.xiaoyu.im.provider.AbstractMessageDataProvider
import com.xiaoyu.im.provider.ConversationManager
import com.xiaoyu.im.util.ChatDraftUtils
import com.xiaoyu.lanling.feature.conversation.viewholder.ConversationListViewHolderManager
import com.xiaoyu.lanling.media.image.ImageLoadParam
import com.xiaoyu.lanling.media.image.UserImageLoadParam

class MainConversationItem(val entity: ConversationEntity) : ConversationListItemBase() {

    val isSingleChat = ConversationType.SINGLE == entity.type
    val user = if (isSingleChat) UserInfoDataProvider.getInstance().fetchFromMemory(entity.toUid) else User.NOBODY
    val lastContentWrapper: LastContentWrapper = buildLastContentWrapper()
    val isTop = entity.topWeight > 0

    private fun buildLastContentWrapper(): LastContentWrapper {
        AbstractMessageDataProvider.loadMessage(entity.lastMessageId)?.let {
            val toUid = entity.toUid
            return if (!TextUtils.isEmpty(toUid) && !TextUtils.isEmpty(ChatDraftUtils.decodeChatDraft(toUid))) {
                val wrapper = LastContentWrapper()
                wrapper.desc = "[草稿] " + ChatDraftUtils.decodeChatDraft(toUid)
                wrapper
            } else {
                ConversationManager.getLastContentWrapper(it)
            }
        }
        return LastContentWrapper()
    }

    val iconLoadParams: ImageLoadParam = if (isSingleChat) {
        UserImageLoadParam.newBuilder().setUserAndDP(user, 56).build()
    } else {
        ImageLoadParam.newBuilder().setUrl(entity.icon).setSizeInDP(56).setRounded(true).build()
    }

    override fun getCompareValue(level: Int): Long {
        return if (level == 2) {
            return if (isTop) entity.topWeight else entity.lastUpdateTime
        } else super.getCompareValue(level)
    }

    override fun getViewType(): Int {
        return ConversationListViewHolderManager.VIEW_TYPE_CONVERSATION
    }

    override fun toString(): String {
        return entity.toString()
    }

    override val newTipCount: Int
        get() = entity.unreadCount


}